package com.goldsprite.microhorigame.ecs.fsms.states;

import com.badlogic.gdx.math.MathUtils;
import com.goldsprite.gameframeworks.ecs.system.GameSystem;
import com.goldsprite.gameframeworks.log.*;
import java.util.*;


public class EntityAttackState extends EntityState {
	protected String animName = "Attack";
	protected List<Integer> attackFrames = new ArrayList<>();
	protected float lastGravityScale, attickingGravityScale = 0.1f;
	private boolean depolyedSlow;
	private float captureSpeed;

	@Override
	public boolean canEnter() {
		return fsm.getInputs().getKeyAttack();
	}

	@Override
	public boolean canExit() {
		boolean cancel = isCancel();
		return fsm.getAnims().isAnimCompleted() || cancel;
	}

	@Override
	public void enter() {
		depolyedSlow = false;
		fsm.getAnims().playAnim(getCurAnimName(), true);
		slowFall();
		//在地面时停住玩家
		if (fsm.isGround()) fsm.getProps().move(0);
	}

	@Override
	public void exit() {
		fsm.getProps().setSpeed(fsm.getProps().getOriSpeed());
		fsm.getAttackTrigger().setEnable(false);
		fsm.getRigi().setGravityScale(lastGravityScale);
	}

	@Override
	public void running() {
		float delta = GameSystem.getDeltaTime();

		int curIndex = fsm.getAnims().curAnimFrameIndex();
		boolean isAttackFrame = attackFrames.contains(curIndex);
		Debug.infoT("GFsm", "当前动画帧索引: %s, 是否攻击帧: %s", curIndex, isAttackFrame);
		fsm.getAttackTrigger().setEnable(isAttackFrame);

		//减缓滑步
		if (fsm.isGround() && !depolyedSlow){
			depolyedSlow = true;
			float oriSpeed = fsm.getProps().getOriSpeed();
			captureSpeed = oriSpeed*0.3f * (fsm.getInputs().getKeySpeedBoost() ? 2 : 1);
			fsm.getProps().setSpeed(captureSpeed);

			fsm.getProps().move(fsm.getInputs().getKeyDirX());
		}
		else if(depolyedSlow){
			float lerpSpeed = MathUtils.lerp(captureSpeed, 0, delta * 2f);
			fsm.getProps().setSpeed(lerpSpeed);
			captureSpeed = lerpSpeed;
			fsm.getProps().move(fsm.getInputs().getKeyDirX());
		}

	}

	public String getCurAnimName(){
		return animName;
	}

	public EntityAttackState setAttackFrames(Integer... indices) {
		attackFrames.clear();
		attackFrames.addAll(Arrays.asList(indices));
		return this;
	}

	public boolean isCancel() {
		int curIndex = fsm.getAnims().curAnimFrameIndex();
		return fsm.getInputs().isMoving() && curIndex >= attackFrames.get(attackFrames.size()-1);
	}

	public void slowFall(){
		lastGravityScale = fsm.getRigi().getGravityScale();
		fsm.getRigi().setGravityScale(lastGravityScale * attickingGravityScale);
		fsm.getRigi().setVelocity(fsm.getRigi().getVelocity().x, 0);
	}
}
